/* global process */
import { useState, useEffect, useMemo, useCallback, memo ,useRef} from 'react';
import { Button, Layout, Menu, theme, message, Modal ,notification} from "antd";
import { useNavigate, Outlet, useLocation } from "react-router-dom";
import { useSelector } from 'react-redux';
import GlobalHeader from "@/components/GlobalHeader";
import logo from '@/static/images/logo.png';
import useSSE from '@/hooks/useSSE';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css'  // 这个nprogress样式必须引入

// 导入对应的Icon
import {
    MenuFoldOutlined,
    MenuUnfoldOutlined
} from '@ant-design/icons';

// 导入公共的Icon映射表
import { IconMap } from '@/utils/iconUtils';

import styles from './index.less'

const { Header, Sider, Content ,Footer } = Layout;


// 配置基础参数
NProgress.configure({ 
    parent: '#root',
    easing: 'ease', 
    speed: 500 ,
    showSpinner: false,// 右侧loading图标
    minimum: 0.1 ,
    trickleSpeed: 200,//递增速度
    trickle: true,//自动递增
});

// Icon映射表已从iconUtils.js导入

const BasicLayout = memo(() => {
    const location = useLocation();
    const navigate = useNavigate();
    const containerRef = useRef(null);

    const [collapsed, setCollapsed] = useState(false);
    const currentUser = useSelector((state) => state.global.userInfo);
    const menulist = useSelector((state) => state.global.menus);
    
    // 使用useMemo缓存isLogin状态，避免每次渲染都重新计算
    const isLogin = useMemo(() => {
        return (localStorage.getItem("access_token") && location.pathname !== "/login") || false;
    }, [location.pathname]);
    const { token: { colorBgContainer, borderRadiusLG }, } = theme.useToken();

    // 使用useEffect处理认证逻辑-缓存历史有效路径
    useEffect(() => {
        // 认证检查和进度条逻辑分离，只在currentUser或isLogin变化时重新执行认证逻辑
        if (!currentUser?.name || !isLogin) {
            message.warning("登录已失效，请重新登录");
            navigate("/login", { replace: true });
            return
        }
    }, [currentUser?.name, isLogin, navigate]);
    // 创建SSE连接的useEffect，只在组件挂载时执行一次
    const clientId = useMemo(() => {
        const existing = localStorage.getItem('client_id');
        if (existing) {return existing;}
        const v = `cid_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
        localStorage.setItem('client_id', v);
        return v;
    }, []);

    const sseurl = useMemo(() => {
        const base = process.env.NODE_ENV === 'production'
            ? 'https://admin.liyq666.top/sse/connect/auth'
            : 'http://localhost:8888/sse/connect/auth';
        const sep = base.includes('?') ? '&' : '?';
        return `${base}${sep}clientId=${encodeURIComponent(clientId)}`;
    }, [clientId]);

    const { subscribe } = useSSE({
        url: sseurl,
        autoconnect: true,
        autoDisconnect: true,
        reconnectDelay: 3000,
        maxReconnectAttempts: Infinity,
        logEvents: process.env.NODE_ENV === 'development',
        useAuth: true,
        enableHeartbeat: true,
    });
    
    
    // 单独的useEffect处理页面加载和路径记录，只在路径变化时执行
    useEffect(() => {
        // 只有在登录状态下才处理进度条和路径记录
        if (currentUser?.name && isLogin) {
            window.process = NProgress;
            
            window.process.start();
            window.process.inc();

            // 清理定时器
            const timer = setTimeout(() => {
                window.process.done();
            }, 1000);

            // 只记录有效页面（如不为 404 页）
            if (location.pathname !== "/login" && location.pathname !== "*") {
                sessionStorage.setItem("lastValidPath", location.pathname);
            }
            
            return () => clearTimeout(timer);
        }
    }, [location.pathname, currentUser?.name, isLogin]);


    /** 选中的菜单项 */
    const selectMenukey = useMemo(() => {
        const path = location.pathname;
        return [path];
    }, [location.pathname]);


    // 将loopMenuItem函数提取到组件外部，避免在useMemo内重复定义
    const processedMenus = useMemo(() => {
        if (!menulist || menulist.length === 0) return [];

        try {
            const cloneMenu = JSON.parse(JSON.stringify(menulist));

            const mapItem = (menuItems) => menuItems
                .map((item) => {
                    const children = Array.isArray(item.children) && item.children.length > 0 ? mapItem(item.children) : undefined;
                    return {
                        key: item.key,
                        label: item.title || item.name || item.label,
                        icon: item.icon && IconMap[item.icon],
                        children,
                    };
                })
                .filter(mi => !!mi.key);

            return mapItem(cloneMenu);
        } catch {
            return [];
        }
    }, [menulist]);


    // 处理窗口resize事件，优化响应式布局
    useEffect(() => {
        // 定义响应式断点常量
        const BREAKPOINT = 1000;
        
        // 检查并设置初始状态
        const checkWindowSize = () => {
            const width = window.innerWidth;
            setCollapsed(width < BREAKPOINT);
        };
        
        // 初始检查
        checkWindowSize();

        // 创建防抖处理函数
        let resizeTimer;
        const handleResize = () => {
            clearTimeout(resizeTimer);
            resizeTimer = setTimeout(checkWindowSize, 500);
        };

        // 添加事件监听器
        window.addEventListener('resize', handleResize, { passive: true });
        
        // 清理函数
        return () => {
            clearTimeout(resizeTimer);
            window.removeEventListener('resize', handleResize, { passive: true });
        };
    }, []); // 移除containerRef依赖，直接使用window.innerWidth



    useEffect(() => {
        const unsubOpen = subscribe('open', (e) => {
            const data = JSON.parse(e?.data || '{}');
            const { connectionId } = data || {};
            if (connectionId) {
                notification.success({ message: 'SSE建立连接成功', description: `连接ID: ${connectionId}` });
            }
        });
        const unsubWelcome = subscribe('welcome', () => {});
        const unsubHeartbeat = subscribe('heartbeat', () => {
            // 处理心跳包
        });
        const unsubLoginout = subscribe('loginout', () => {
            // 处理登录/退出事件
            Modal.warning({
                title: '登录异常',
                content: '您已在其他地方登录或被强制注销，当前登录已失效，请重新登录！',
                onOk() {
                    localStorage.clear();
                    navigate('/login', { replace: true });
                },
            });
        });
        const unsubMessage = subscribe('message', () => {
            // 处理消息
        });
        const unsubError = subscribe('error', (err) => {
            if (err && err.status === 401) {
                // 身份验证不通过
            }
        });

        return () => {
            unsubOpen && unsubOpen();
            unsubWelcome && unsubWelcome();
            unsubHeartbeat && unsubHeartbeat();
            unsubLoginout && unsubLoginout();
            unsubMessage && unsubMessage();
            unsubError && unsubError();
        };
    }, [subscribe, navigate]);
    

    return (
        <Layout className={styles.layoutbox} ref={containerRef}>
            <Sider theme={"dark"} trigger={null} collapsible collapsed={collapsed}>
                <div className={styles.logobox}>
                    <img src={logo} alt="logo" />
                    {!collapsed?<span>{currentUser?.name}</span>:null}
                </div>
                <Menu
                    theme="dark"
                    mode="inline"
                    defaultSelectedKeys={["/"]}
                    selectedKeys={selectMenukey}
                    // 使用useCallback缓存点击事件处理函数
                    onClick={useCallback(({ key }) => {
                        navigate(key);
                    }, [navigate])}
                    style={{
                        height: "90%",
                        overflow: "auto",
                        borderRight: 0,
                    }}
                    items={processedMenus}
                />
            </Sider>
            <Layout>
                <Header
                    className={styles.headerbox}
                    style={{
                        background: colorBgContainer,
                    }}
                >
                    <Button
                        type="text"
                        icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
                        // 使用函数式更新避免依赖collapsed状态
                    onClick={useCallback(() => {
                        setCollapsed(prev => !prev);
                    }, [])}
                        style={{
                            fontSize: "16px",
                            width: 64,
                            height: 64,
                        }}
                    />
                    <GlobalHeader currentUser={currentUser} />
                </Header>
                <Content
                    className={styles.contentbox}
                    style={{
                        background: colorBgContainer,
                        borderRadius: borderRadiusLG,
                    }}
                >
                    {/* <AuthRoute> */}
                        <Outlet />
                    {/* </AuthRoute> */}
                    
                </Content>
                <Footer style={{ textAlign: 'center',paddingTop:0 ,height:30}}>
                    React + Redux + React-router + Ant Design © 2025  豫ICP备19036863号
                </Footer>
            </Layout>
        </Layout>
    );
});
export default BasicLayout;
